<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>图片加载回调函数</title>
</head>
<body>
  <script>
    // 回调函数写法
    // function loadImg(src, callback, fail) {
    //   const img = document.createElement('img')
    //   img.onload = function() {
    //     callback(img)
    //   }
    //   img.onerror = function() {
    //     fail()
    //   }
    //   img.src = src
    // }

    // const src = 'https://www.imooc.com/static/img/index/logo.png'
    // loadImg(src, function(img) {
    //   console.log(img.width)
    // }, function() {
    //   console.log('图片加载错误')
    // })

    // promise 写法
    function loadImg(src) {
      const promise = new Promise((resovle, reject) => {
        const img = document.createElement('img')
        img.onload = function() {
          resovle(img)
        }
        img.onerror = function () {
          reject(img)
        }
        img.src = src
      })
      return promise
    }

    const src= 'https://www.imooc.com/static/img/index/logo.png'
    loadImg(src).then((img) => {
      console.log(img.height)
    }).then((img) => {
      console.log(img)
    })
  </script>
</body>
</html>